<!-- 用户管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 用户列表 -->
      <el-col>
        <!-- 搜索区域 -->
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto">
            <el-form-item label="关键字" prop="keywords">
              <el-input
                v-model="queryParams.name"
                placeholder="用户名/昵称/手机号"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item class="search-buttons">
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="hover" class="data-table">
          <div class="data-table__toolbar">
            <div class="data-table__toolbar--actions">
              <el-button
                v-hasPerm="['sys:user:add']"
                type="success"
                icon="plus"
                @click="handleOpenDialog()"
              >
                新增
              </el-button>
            </div>
          </div>

          <el-table
            v-loading="loading"
            :data="pageData"
            border
            stripe
            highlight-current-row
            class="data-table__content"
            align="center"
          >
            <!-- 自定义空状态 -->
            <template #empty>
              <div style="padding: 60px 0; text-align: center">
                <el-empty description="暂无数据" />
              </div>
            </template>
            <el-table-column label="商户名" prop="name" align="center" />
            <el-table-column label="联系电话" prop="phone" />
            <el-table-column label="联系地址" prop="address" align="center" />
            <el-table-column label="创建时间" align="center" prop="createTime" />
            <el-table-column label="操作" fixed="right" width="190">
              <template #default="scope">
                <el-button
                  v-hasPerm="'sys:user:passban'"
                  type="primary"
                  :icon="scope.row.status === 1 ? 'Lock' : 'Unlock'"
                  link
                  size="small"
                  @click="banAccount(scope.row.status === 1 ? 0 : 1, scope.row.id)"
                >
                  {{ scope.row.status === 1 ? "禁用" : "启用" }}
                </el-button>
                <el-button
                  v-hasPerm="'sys:user:edit'"
                  type="primary"
                  icon="edit"
                  link
                  size="small"
                  @click="handleOpenDialog(scope.row.id)"
                >
                  编辑
                </el-button>
                <el-button
                  v-hasPerm="'sys:user:delete'"
                  type="danger"
                  icon="delete"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.page"
            v-model:limit="queryParams.pageSize"
            @pagination="fetchData"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户表单 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      :size="drawerSize"
      :close-on-click-modal="false"
      @close="handleCloseDialog"
    >
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="商户名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入商户名" />
        </el-form-item>

        <el-form-item label="商户编号" prop="code">
          <el-input v-model="formData.code" placeholder="请输入商户编号" />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入联系电话" maxlength="11" />
        </el-form-item>

        <el-form-item label="鱼种" prop="fish">
          <el-input v-model="formData.fish" placeholder="请输入鱼种" />
        </el-form-item>

        <el-form-item label="选择水库" prop="reservoirId">
          <el-select v-model="formData.reservoirId" placeholder="请选择" style="width: 240px">
            <el-option
              v-for="item in reservoirList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
            <pagination
              v-if="reservoirTotal > 0"
              v-model:total="reservoirTotal"
              v-model:page="reservoirReqData.page"
              v-model:limit="reservoirReqData.pageSize"
              @pagination="getReservoirList"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所在区域" prop="area">
          <el-select
            v-model="formData.province"
            placeholder="请选择省份"
            style="width: 32%; margin-right: 2%"
            @change="handleChangeProvince"
          >
            <el-option
              v-for="item in addressList.province"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select
            v-if="addressData.city.provinceCode"
            v-model="formData.city"
            placeholder="请选择城市"
            style="width: 32%; margin-right: 2%"
            @change="handleChangeCity"
          >
            <el-option
              v-for="item in addressList.city"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select
            v-if="addressData.area.cityCode"
            v-model="formData.area"
            placeholder="请选择区县"
            style="width: 32%"
            @change="handleChangeArea"
          >
            <el-option
              v-for="item in addressList.area"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="门店地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入联系地址" />
        </el-form-item> -->

        <el-form-item label="关键字搜索">
          <div style="width: 100%">
            <div class="search_box">
              <el-select
                v-model="selectedAddress"
                filterable
                remote
                reserve-keyword
                placeholder="请输入地址"
                :remote-method="remoteAddressSearch"
                :loading="searchLoading"
                style="width: 100%"
                @change="handleAddressSelect"
              >
                <el-option
                  v-for="item in addressOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </div>
            <div id="gaode_Map" ref="gaode_Map"></div>
          </div>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请填写地址" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="formData.longitude" disabled placeholder="请填写地址" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="formData.latitude" disabled placeholder="请填写地址" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from "@/store/modules/app-store";
import { DeviceEnum } from "@/enums/settings/device-enum";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, watch, onMounted, computed } from "vue";
import MerchantAPI from "@/api/system/merchant";
import CommonAPI from "@/api/common";
// 引入高德地图相关
import AMapLoader from "@amap/amap-jsapi-loader";

// 设置安全密钥
window._AMapSecurityConfig = {
  securityJsCode: "f5c65b8d8959a6b6b8765e052d107dc2",
};
defineOptions({
  name: "MerchantIndex",
  inheritAttrs: false,
});

// 地图相关变量
const input = ref("");
const selectedAddress = ref("");
const addressOptions = ref<Array<{ value: string; label: string }>>([]);
const searchLoading = ref(false);
const map = ref<any>(null);
const placeSearch = ref<any>(null);
const lnglat = ref<any[]>([]);
const markers = ref<any[]>([]);
const position = ref<any>({});
const gaode_Map = ref<HTMLElement>();
const addressCache = ref<Map<string, any>>(new Map());

const appStore = useAppStore();

const queryFormRef = ref();
const userFormRef = ref();

const queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: "",
});

const pageData = ref<any[]>([]);
const total = ref(0);
const loading = ref(false);

const dialog = reactive({
  visible: false,
  title: "新增商户",
});

const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"));

const formData = reactive({
  name: "",
  code: "",
  phone: "",
  address: "",
  area: "",
  city: "",
  province: "",
  longitude: 0,
  latitude: 0,
  fish: "",
  reservoirId: null,
  id: null as number | null,
});
const addressList = ref({
  province: [
    {
      value: "",
      label: "请选择省份",
    },
  ],
  city: [
    {
      value: "",
      label: "请选择城市",
    },
  ],
  area: [
    {
      value: "",
      label: "请选择区县",
    },
  ],
});
const addressData = ref({
  province: {
    page: 1,
    pageSize: 50,
  },
  city: {
    provinceCode: "",
    page: 1,
    pageSize: 50,
  },
  area: {
    cityCode: "",
    page: 1,
    pageSize: 50,
  },
});

const rules = reactive({
  name: [{ required: true, message: "商户名不能为空", trigger: "blur" }],
  code: [{ required: true, message: "商户编号不能为空", trigger: "blur" }],
  phone: [
    {
      required: true,
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  address: [{ required: true, message: "地址不能为空", trigger: "blur" }],
  area: [{ required: true, message: "省市区不能为空", trigger: "blur" }],
  city: [{ required: true, message: "城市不能为空", trigger: "blur" }],
  province: [{ required: true, message: "省份不能为空", trigger: "blur" }],
  fish: [{ required: true, message: "鱼种不能为空", trigger: "blur" }],
  reservoirId: [{ required: true, message: "水库不能为空", trigger: "blur" }],
});
const reservoirList = ref<any[]>([]);
const reservoirTotal = ref(0);
const reservoirReqData = reactive({
  page: 1,
  pageSize: 10,
});

// 当弹窗打开时初始化地图
watch(
  () => dialog.visible,
  (newVal) => {
    if (newVal) {
      // 延迟初始化地图，确保DOM已渲染
      setTimeout(() => {
        initMap();
      }, 100);
    }
  }
);

// 地图初始化
function initMap() {
  let centerLen = [104.065843, 30.657116];
  // 如果有已有坐标，使用已有坐标作为中心点
  if (formData.longitude && formData.latitude) {
    centerLen = [formData.longitude, formData.latitude];
  }

  AMapLoader.load({
    key: "b7f379b67cd6962e46be2337d681a683", // 申请好的Web端开发者Key
    version: "2.0",
    plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder"],
  })
    .then((AMap: any) => {
      if (!gaode_Map.value) return;

      map.value = new AMap.Map(gaode_Map.value, {
        zoom: 18, // 初始化地图级别
        center: centerLen, // 中心点坐标
        resizeEnable: true,
      });

      // 设置初始标记
      setMarker(centerLen);

      // 初始化搜索功能
      searchMap(AMap);

      // 监听地图点击事件
      map.value.on("click", clickMapHandler);
    })
    .catch((e: any) => {
      console.error("地图初始化失败:", e);
    });
}

// 初始化搜索功能
function searchMap(AMap: any) {
  // 构造地点查询类
  placeSearch.value = new AMap.PlaceSearch({
    map: map.value,
    city: "全国",
    pageSize: 10,
    pageIndex: 1,
  });
}

// 远程地址搜索方法
function remoteAddressSearch(query: string) {
  if (!query.trim()) {
    addressOptions.value = [];
    return;
  }

  // 检查缓存
  if (addressCache.value.has(query)) {
    addressOptions.value = addressCache.value.get(query);
    return;
  }

  searchLoading.value = true;
  addressOptions.value = [];

  // 使用高德地图的PlaceSearch进行搜索
  if (placeSearch.value) {
    placeSearch.value.search(query, (status: string, result: any) => {
      searchLoading.value = false;
      if (status === "complete" && result.poiList && result.poiList.pois.length > 0) {
        const options = result.poiList.pois.map((item: any) => ({
          value: JSON.stringify({
            lng: item.location.lng,
            lat: item.location.lat,
            address: `${item.pname}${item.cityname}${item.adname}${item.address}${item.name}`,
            name: item.name,
            district: item.district,
          }),
          label: `${item.pname}${item.cityname}${item.adname}${item.address}${item.name}`,
        }));
        addressOptions.value = options;
        // 缓存结果
        addressCache.value.set(query, options);
      }
    });
  } else {
    searchLoading.value = false;
  }
}

// 处理地址选择
function handleAddressSelect(value: string) {
  if (!value) return;

  try {
    const addressInfo = JSON.parse(value);
    formData.longitude = addressInfo.lng;
    formData.latitude = addressInfo.lat;
    console.log("选择的地址信息:", addressInfo);
    formData.address = `${addressInfo.address}`;

    // 设置标记和地图中心
    setMarker([addressInfo.lng, addressInfo.lat]);
    if (map.value) {
      map.value.setCenter([addressInfo.lng, addressInfo.lat]);
    }
  } catch (e) {
    console.error("解析地址信息失败:", e);
  }
}

// 点击地图事件获取经纬度，并添加标记
function clickMapHandler(e: any) {
  const info = e.lnglat;
  formData.longitude = info.lng;
  formData.latitude = info.lat;
  lnglat.value = [info.getLng(), info.getLat()];

  setMarker(lnglat.value);

  // 根据经纬度转换成详细地址
  const geocoder = new AMap.Geocoder({
    city: "全国",
  });

  geocoder.getAddress(lnglat.value, function (status: string, result: any) {
    if (status === "complete" && result.regeocode) {
      formData.address = result.regeocode.formattedAddress;
      input.value = formData.address; // 把查询到的地址赋值到输入框
    }
  });

  position.value = {
    longitude: info.getLng(),
    latitude: info.getLat(),
    address: formData.address,
  };
}

// 添加标记
function setMarker(lnglat: any[]) {
  removeMarker();
  if (!map.value) return;

  const marker = new AMap.Marker({
    position: lnglat,
  });

  marker.setMap(map.value);
  markers.value.push(marker);
}

// 删除之前的标记点
function removeMarker() {
  if (map.value && markers.value.length > 0) {
    map.value.remove(markers.value);
    markers.value = [];
  }
}

// 获取数据
async function fetchData() {
  loading.value = true;
  try {
    const data = await MerchantAPI.list(queryParams);
    // console.log(data);
    pageData.value = data.data.records;
    total.value = data.data.total;
  } finally {
    loading.value = false;
  }
}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.page = 1;
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  queryParams.name = "";
  fetchData();
}

// 禁用/启用账号
async function banAccount(status: any, id: any) {
  MerchantAPI.changeStatus({ status, id }).then(() => {
    ElMessage.success(status === 1 ? "启用商户成功" : "禁用商户成功");
    handleResetQuery();
  });
}

/**打开弹窗
 * @param id 用户ID
 */
async function handleOpenDialog(id?: string) {
  if (id) {
    dialog.title = "修改商户";
    MerchantAPI.detail(id).then((data) => {
      console.log(data.data);
      Object.assign(formData, { ...data.data });
      // formData.password = "";
      addressData.value.city.provinceCode = data.data.province;
      addressData.value.area.cityCode = data.data.city;
      getAddressList("city");
      getAddressList("area");
    });
  } else {
    dialog.title = "新增商户";
  }
  dialog.visible = true;
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.id = null;
  selectedAddress.value = "";
  addressOptions.value = [];
  Object.assign(formData, {
    name: "",
    code: "",
    phone: "",
    address: "",
    area: "",
    city: "",
    province: "",
    longitude: 0,
    latitude: 0,
  });
}

// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (userId) {
        MerchantAPI.update(formData)
          .then(() => {
            ElMessage.success("修改商户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        console.log(formData);
        MerchantAPI.add(formData)
          .then(() => {
            ElMessage.success("新增商户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

/**删除用户
 * @param id  用户ID
 */
function handleDelete(id: any) {
  console.log("删除商户ID:", id);
  ElMessageBox.confirm("确认删除当前商户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      MerchantAPI.delMerchant(id)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

async function getAddressList(name: string) {
  if (name == "province") {
    const res = await CommonAPI.proList(addressData.value[name]);
    if (res.code !== 200){
		return ElMessage.error(res.data.msg || "获取省份列表失败");
	}
    addressList.value.province = res.data.records;
    console.log(res);
  }
  if (name == "city") {
    const res2 = await CommonAPI.cityList(addressData.value[name]);
    if (res2.code !== 200){
		return ElMessage.error(res2.data.msg || "获取城市列表失败");
	}
    addressList.value.city = res2.data.records;
    console.log(res2);
  }
  if (name == "area") {
    const res3 = await CommonAPI.areaList(addressData.value[name]);
    if (res3.code !== 200){
		return ElMessage.error(res3.data.msg || "获取区县列表失败");
	}
    addressList.value.area = res3.data.records;
    console.log(res3);
  }
}

function handleChangeProvince(e: any) {
  console.log(e);
  addressData.value.city.provinceCode = e;
  formData.province = e;
  getAddressList("city");
}

function handleChangeCity(e: any) {
  console.log(e);
  addressData.value.area.cityCode = e;
  formData.city = e;
  getAddressList("area");
}

function handleChangeArea(e: any) {
  console.log(e);
  formData.area = e;
}

async function getReservoirList() {
  const res = await MerchantAPI.opsList(reservoirReqData);
  if (res.code !== 200) return ElMessage.error(res.data.msg || "获取水库列表失败");
  reservoirList.value = res.data.records.map((item: any) => ({
    value: item.id,
    label: item.name,
  }));
  reservoirTotal.value = res.data.total;
  console.log(reservoirList);
}

onMounted(() => {
  handleQuery();
  getAddressList("province");
  getReservoirList();
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/** 高德地图样式*/
#gaode_Map {
  overflow: hidden;
  width: 100%;
  height: 300px;
  margin: 10px 0;
  border: 1px solid #ebeef5;
}

.search_box {
  margin-bottom: 10px;
}

/**确保输入框样式统一*/
.search_box :deep(.el-input__wrapper) {
  border-radius: 4px;
}
</style>
